package com.iretailer.report.analyze.flow.device;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iretailer.report.analyze.annotation.AnalyzeClass;
import com.iretailer.report.analyze.commonModel.InOutMetric;
import com.iretailer.report.analyze.commonModel.PassengerFlowModel;
import com.iretailer.report.analyze.commonUtil.ResponeResultType;
import com.iretailer.report.analyze.commonUtil.Xml2JSONUtil;
import com.iretailer.report.analyze.flow.Flow;
import com.iretailer.report.analyze.flow.Xml2Data;
import com.iretailer.report.util.StringUtil;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.HttpContent;
import io.netty.util.CharsetUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 海康设备
 */
@Slf4j
@AnalyzeClass
@Component("hikvision")
public class HikVision extends Flow implements Xml2Data {

    @Value("${netty.path.hikvision}")
    private String hikvision;

    @Override
    public String[] analyzePath() {
        if (StringUtil.notEmpty(hikvision)) {
            return hikvision.split(",");
        } else {
            return new String[]{"/hikvision"};
        }
    }

    private DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX");

    @SneakyThrows
    @Override
    public PassengerFlowModel transformation(String context, Map<String, Object> paramsMap) {
        JSONObject object = Xml2JSONUtil.documentToJSONObject(context);

        assert object != null;
        System.out.println(object.toJSONString());
        PassengerFlowModel flow = new PassengerFlowModel();
        LocalDateTime datetime = LocalDateTime.parse(object.getString("dateTime"), dtf);
        flow.setDeviceType("hikvision");
        flow.setDeviceId(object.getString("channelName"));
        flow.setIpAddress(object.getString("ipAddress"));
        flow.setDeviceName(object.getString("channelName"));
        flow.setMacAddress(object.getString("macAddress"));
        List<InOutMetric> inOutMetrics = new ArrayList<>();
        JSONArray peopleCounting = object.getJSONArray("peopleCounting");
        for (int r = 0; r < peopleCounting.size(); r++) {
            JSONObject jsonObject = peopleCounting.getJSONObject(r);
            String statisticalMethods = jsonObject.getString("statisticalMethods");
            if ("realTime".equals(statisticalMethods)) {
                return flow;
            }
            InOutMetric inOutMetric = new InOutMetric();
            inOutMetric.setZone(object.getString("channelID"));
            inOutMetric.setEnter(Integer.parseInt((String) jsonObject.get("enter")));
            inOutMetric.setExit(Integer.parseInt((String) jsonObject.get("exit")));
            JSONObject timeRange = jsonObject.getJSONArray("TimeRange").getJSONObject(0);
            inOutMetric.setDate(datetime.toLocalDate());
            inOutMetric.setStartTime(LocalDateTime.parse(timeRange.getString("startTime"), dtf).toLocalTime());
            inOutMetric.setEndTime(LocalDateTime.parse(timeRange.getString("endTime"), dtf).toLocalTime());
            inOutMetrics.add(inOutMetric);
        }
        flow.setInOutMetrics(inOutMetrics);
        return flow;
    }

    @Override
    public void deviceTypeDiff(JSONObject object, PassengerFlowModel flow) {
    }

    @Override
    public void dataDiff(JSONArray reports, PassengerFlowModel flow) {
    }


    @Override
    public ResponeResultType nettyAnalyze(Map<String, Object> paramsMap, Object msg) {
        if (msg instanceof HttpContent) {
            HttpContent httpContent = (HttpContent) msg;
            ByteBuf byteBuf = httpContent.content();
            if (byteBuf != null) {
                String data = byteBuf.toString(CharsetUtil.UTF_8);
                PassengerFlowModel pfm = transformation(data, paramsMap);
                return flowInsert.analysisCommon(pfm);
            } else {
                log.error("----- ByteBuf is null. {}", paramsMap.get("remoreAddr"));
                return ResponeResultType.getBadRequest(ResponeResultType.CFLType.CLOSE);
            }
        } else {
            return ResponeResultType.getBadRequest(ResponeResultType.CFLType.CLOSE);
        }
    }


}
